package cn.enjoyedu.ch1.pool;

import java.sql.Connection;
import java.util.LinkedList;
import java.util.List;

/**
 * @author: xiaofu
 * @DESCRIPTION: a technology seeker
 * @date: 2020-02-27 23:28
 */
public class MyPool {
    private LinkedList<Connection> pool = new LinkedList<>();//连接池

    //线程从连接池获取连接
    public Connection getConection() throws InterruptedException {
        synchronized (pool) {
            while (pool.isEmpty()) {
                //连接池为空时,等待连接池有链接
                pool.wait();
            }
            Connection connection=null;
            if (!pool.isEmpty()){connection=pool.removeFirst();}//遵循先进先出
            return connection;
        }
    }
    //释放的连接放入连接池
    public void releaseConnection(Connection connection) {
        if (connection != null) {
            synchronized (pool) {
                pool.addLast(connection);
                //连接池有连接时,通知正在等待的线程
                pool.notifyAll();
            }
        }
    }
}
